let logger = require("pomelo-logger").getLogger(__filename);
const GAME_RECORD_COLLECTION_NAME = "gameRecords";

let Dao = function (app) {
    this.app = app;
};

Dao.prototype.findByPlayerId = function (uid, time, callback) {
    let dbClient = this.app.get("gameDBClient");
    logger.info(`findByPlayerId uid=${uid}, time=${time}`);
    dbClient.collection(GAME_RECORD_COLLECTION_NAME, function (error, collection) {
        if (!!error) {
            logger.error("find gameRecord failed. get collection error. error=" + error);
            callback([]);
            return;
        }
        collection.find({
            playerScores : {$elemMatch : {uid : uid}},
            time: {$gt : time}
        })
        .sort({"time" : -1})
        .limit(30)
        .toArray(function (error, documents) {
            if (!!error) {
                logger.error("getMaxUid failed. toArray. error=" + error);
                callback([]);
                return;
            }
            logger.info(`findByPlayerId documents=${JSON.stringify(documents)}`);
            if (documents.length === 0) {
                logger.warn("getMaxUid failed. document length is 0");
                callback([]);
                return;
            }
            callback(documents);
        });
    });
};

Dao.prototype.addGameRecord = function (document, callback) {
    let dbClient = this.app.get("gameDBClient");
    dbClient.collection(GAME_RECORD_COLLECTION_NAME, function (error, collection) {
        if (!!error) {
            logger.error(`insert player failed. error=${error}`);
            callback(null);
            return;
        }
        collection.insert(document, function (error, result) {
            if (!!error) {
                logger.error(`insert player failed. error=${error}`);
                callback(null);
                return;
            }
            callback(result);
        });
    });
};

module.exports.create = function (app) {
    return new Dao(app);
};
